# from django.http import HttpResponse
#
# def hello(request):
#     return HttpResponse('Hello World!')
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, HttpResponse
from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO


# 临时关闭csrf
@csrf_exempt
def runoob(request):

    # templates中可以通过.下标的形式获取对应的值(列表)
    # views_list = ["菜鸟教程1","菜鸟教程2","菜鸟教程3"]
    # 对于字典形式的话可以通过.名称的形式获取对应的值
    # views_dict = {"name":"BIGDATA"}
    # import datetime
    # now = datetime.datetime.now()
    # views_dict = [{"name":"zhangsan","age":18},{"name":"lisi","age":16},{"name":"wangwu","age":19}]
    # views_list = ["a", "b", "c", "d", "e"]
    # views_list = []
    # return render(request,'runoob.html', {'listvar': views_list})
    # unsafe_html = "<strong>加粗文本</strong>"
    # safe_html = mark_safe("<strong>加粗文本</strong>")  # 标记为安全
    # return render(request, "runoob.html", {"unsafe_html": unsafe_html, "safe_html": safe_html})
    # name = "菜鸟"
    # return render(request, 'runoob.html', {'name':name})

    # print(request.method)
    # print(request.GET)
    # print(request.POST)
    # print(request.META)
    # if request.user.is_authenticated:
    #     print(request.user)
    #     return render(request, 'user.html')
    # else:
    #     print("未登录，请登录")
    #     return render(request, 'login.html')

    # name = request.GET.get('name')
    # return HttpResponse('Hello, %s!' % name)

    # name = request.POST.get('name')
    # return HttpResponse('姓名：{}'.format(name))

    # name = request.body
    # name = request.path
    # print(name)
    # return HttpResponse("Hello World")

    # return HttpResponse("菜鸟教程")
    return HttpResponse("<a href='https://www.runoob.com/'>菜鸟教程</a>")

def index(request):
    print(request)
    return HttpResponse('菜鸟教程')

def index(request, year):
    print(year)
    return HttpResponse('test')

def get_valid_img(request):
    # 生成随机验证码
    def random_color():
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    img = Image.new("RGB", (120, 30), random_color())
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("arial.ttf", 25)

    valid_code = "".join(random.sample("ABCDEFGHJKLMNPQRSTUVWXYZ123456789", 4))  # 生成4位验证码
    draw.text((10, 0), valid_code, fill=random_color(), font=font)

    # 将验证码存入 session
    request.session["keep_str"] = valid_code

    # 将图片返回给前端
    buffer = BytesIO()
    img.save(buffer, format="PNG")
    return HttpResponse(buffer.getvalue(), content_type="image/png")

def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    else:
        cookies = request.COOKIES.values()
        print("当前请求的所有的cookie", cookies,type(cookies))
        username = request.POST.get('username')
        pwd = request.POST.get('password')
        valid_num = request.POST.get('valid_number')
        keep_str = request.session.get("keep_str")
        if keep_str and keep_str.upper() == valid_num.upper():
            user = auth.authenticate(username=username, password=pwd)
            if user:

                return HttpResponse("登录成功")
            else:
                return HttpResponse("用户名或密码错误")
        else:
            return HttpResponse("验证码错误")

@csrf_exempt
def add_user(request):
    # 创建一个普通用户，密码是密文， 并不会对密码的格式进行校验
    # User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password'])
    # User.objects.create(username=request.POST['username'], password=request.POST['password'])
    User.objects.create_superuser(request.POST['username'], request.POST['email'], request.POST['password'])
    return HttpResponse("SUCCESS")